import axios from 'axios'

// Axios instance shared by all activity related requests
const api = axios.create({
  baseURL: '/api',
  timeout: 600000,
  headers: {
    'Content-Type': 'application/json'
  },
  withCredentials: true,
  transformResponse: [
    function (data) {
      try {
        // Parse JSON and stringify big integers to prevent precision loss
        return JSON.parse(data, (key, value) => {
          if (typeof value === 'number' && Math.abs(value) > 1e15) {
            return String(value)
          }
          return value
        })
      } catch (e) {
        return data
      }
    }
  ]
})

// Attach token if present
api.interceptors.request.use(
    (config) => {
      const token = localStorage.getItem('token')
      if (token) {
        config.headers.Authorization = `Bearer ${token}`
      }
      return config
    },
    (error) => Promise.reject(error)
)

// Unwrap response payload and handle unauthorised access
api.interceptors.response.use(
    (response) => response.data,
    (error) => {
      if (error.response?.status === 401) {
        localStorage.removeItem('token')
        window.location.href = '/login'
      }
      return Promise.reject(error)
    }
)

const cleanPayload = (payload) => {
  const result = { ...payload }
  Object.keys(result).forEach((key) => {
    const value = result[key]
    if (value === '' || value === null || value === undefined) {
      delete result[key]
    }
  })
  return result
}

const normaliseActivityPayload = (activityData, options = {}) => {
  const { includeId = false, defaultStatus } = options
  const payload = {}

  if (includeId && activityData.id !== undefined) {
    payload.id = activityData.id
  }

  if (activityData.title !== undefined) {
    payload.title = activityData.title
  }
  if (activityData.content !== undefined) {
    payload.content = activityData.content
  }
  if (activityData.location !== undefined) {
    payload.location = activityData.location
  }
  if (activityData.coverImage !== undefined || activityData.image !== undefined) {
    payload.coverImage = activityData.coverImage || activityData.image
  }

  const quota = Number(activityData.quota)
  if (Number.isFinite(quota)) {
    payload.quota = quota
  }

  const status = Number(activityData.status)
  if (Number.isFinite(status)) {
    payload.status = status
  } else if (defaultStatus !== undefined) {
    payload.status = defaultStatus
  }

  const start = activityData.startTime || activityData.time
  const end = activityData.endTime || activityData.time
  if (start) {
    payload.startTime = start
  }
  if (end) {
    payload.endTime = end
  }

  return cleanPayload(payload)
}

// Activity list with pagination
export const getActivities = async (params = {}) => {
  try {
    const { current = 1, size = 10, ...otherParams } = params
    const requestParams = {
      current: Number(current),
      size: Number(size),
      ...otherParams
    }

    console.log('getActivities request params:', requestParams)
    const response = await api.get('/activity/page', {
      params: requestParams
    })
    console.log('getActivities response:', response)
    return response
  } catch (error) {
    console.error('Failed to fetch activity list:', error.response?.data || error.message)
    const errorMessage = error.response?.data?.message || error.message || '获取活动列表失败'
    throw new Error(errorMessage)
  }
}

// Submit an enrolment request
export const enrollActivity = async (activityId, userInfo) => {
  try {
    const response = await api.post(`/activity/${activityId}/enroll`, userInfo)
    return response
  } catch (error) {
    console.error('Activity enrolment failed:', error)
    throw error
  }
}

// 新增活动(admin)
export const addActivity = async (activityData) => {
  try {
    const payload = normaliseActivityPayload(activityData, { defaultStatus: 1 })
    console.log('addActivity payload:', JSON.stringify(payload, null, 2))

    const response = await api.post('/activity/create', payload)
    console.log('addActivity response:', response)
    return response
  } catch (error) {
    let errorMessage = '添加活动失败'
    if (error.response) {
      console.error('addActivity error detail:', {
        status: error.response.status,
        data: error.response.data,
        message: error.response.data?.message || error.response.statusText
      })
      errorMessage = error.response.data?.message || `添加活动失败: ${error.response.statusText}`
    } else {
      console.error('addActivity unexpected error:', error)
    }
    throw new Error(errorMessage)
  }
}

// 更新活动(admin)
export const updateActivity = async (activityId, activityData) => {
  try {
    const payload = normaliseActivityPayload(
        { ...activityData, id: activityId },
        { includeId: true }
    )
    const response = await api.put('/activity/update', payload)
    return response
  } catch (error) {
    console.error('更新活动失败:', error)
    throw error
  }
}

// 删除活动(admin)
export const deleteActivity = async (activityId) => {
  try {
    const response = await api.delete(`/activity/${activityId}`)
    return response
  } catch (error) {
    console.error('删除活动失败:', error)
    throw error
  }
}

// 获取活动详情
export const getActivityById = async (activityId) => {
  try {
    const response = await api.get(`/activity/detail/${activityId}`)
    return response
  } catch (error) {
    console.error('获取活动详情失败:', error)
    throw error
  }
}

// 更新活动状态
export const updateActivityStatus = async (activityId, status) => {
  try {
    const response = await api.put(`/activity/status/${activityId}`, null, {
      params: { status }
    })
    return response
  } catch (error) {
    console.error('更新活动状态失败:', error)
    throw error
  }
}
